package com.mj.mes.system.SysUser;

import com.mj.mes.config.shiro.CheckPermission;
import com.mj.mes.config.shiro.PasswordHelper;
import com.mj.mes.system.SysRole.SysRole;
import com.mj.mes.system.SysRole.SysRoleService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Administrator on 2017/3/16.
 */
@Controller
@RequestMapping("user")
public class SysUserController {
    private static Logger logger=Logger.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private PasswordHelper passwordHelper;
    /**
     * 带分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "queryWithPaging")
    @ResponseBody
    @CheckPermission(permission={"user:view"})
    public Map<String, Object> findAll(Integer page, @RequestParam(value = "rows") Integer size) {
        Map<String, Object> map = new HashedMap();
        Page<SysUser> list = sysUserService.findAll(new PageRequest(page - 1, size));
        int total = sysUserService.findAll().size();
        map.put("total", total);
        map.put("rows", list.getContent());
        return map;
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"user:delete"})
    public Map<String, String> deleteUser(String ids) {
        Map<String, String> map = new HashedMap();
        String[] idArrayList = ids.split(",");
        List<SysUser> list = new ArrayList<SysUser>();
        for (int i = 0; i < idArrayList.length; i++) {
            SysUser sysUser = new SysUser();
            sysUser.setId(Long.valueOf(idArrayList[i]));
            list.add(sysUser);
        }
        boolean flag = sysUserService.delete(list);
        if (flag) {
            map.put("msg", "success");
        } else {
            map.put("msg", "fail");
        }
        return map;
    }

    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    @CheckPermission(permission={"user:update"})
    public String toUpdateUser(SysUser sysUser, Model model) {
        sysUser = sysUserService.findOne(sysUser.getId());
        String roleNames="";
        String roleIds="";
        if(sysUser.getRoles().size()!=0){
            for (SysRole role : sysUser.getRoles()) {
                roleNames=role.getRoleName()+","+roleNames;
                roleIds=role.getId()+","+roleIds;
            }
            roleIds=roleIds.substring(0,roleIds.length()-1);
            roleNames=roleNames.substring(0,roleNames.length()-1);
            model.addAttribute("roleNames", roleNames);
            model.addAttribute("roleIds", roleIds);
        }
        model.addAttribute("id", sysUser.getId());
        model.addAttribute("userName", sysUser.getUserName());
        model.addAttribute("userAvailable", sysUser.getUserAvailable());
        return "user/userEdit";
    }

    /**
     * 角色查询
     * @param sysRole
     * @param page
     * @param rows
     * @param size
     * @return
     */
    @RequestMapping(value = "roleFindAllWithPaging", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> findAllWithPaging(SysRole sysRole, Integer page, Integer rows, @RequestParam(value = "rows") Integer size) {
        Map<String, Object> map = new HashedMap();
        Page<SysRole> list = sysRoleService.findAll(new PageRequest(page - 1, size));
        int total = sysRoleService.findAll().size();
        map.put("total", total);
        map.put("rows", list.getContent());
        return map;
    }

    /**
     * 更改用户
     * @param sysUser
     * @param roleIds
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"user:update"})
    public Map<String, String> updateUser(SysUser sysUser, @Param("roleIds") String roleIds) {
        Map<String, String> map = new HashedMap();
//        System.out.println(roleIds+"    "+sysUser.getId());
       //如果密码为空的话，说明用户没有修改密码，需要从数据库中查询出来
        if (sysUser.getUserPassword()==null||"".equals(sysUser.getUserPassword())){
            sysUser= sysUserService.findOne(sysUser.getId());
        }else {
            passwordHelper.encryptPassword(sysUser);
        }
        //获取角色的id
        String[] roleIdArray = roleIds.split(",");
        List<Long> roleIdsList = new ArrayList<>();
        for (int i = 0; i < roleIdArray.length; i++) {
            roleIdsList.add(Long.valueOf(roleIdArray[i]));
        }
        List<SysRole> roleList = sysRoleService.findAll(roleIdsList);
        Set<SysRole> sysRoles = new HashSet<>(roleList);
        sysUser.setRoles(sysRoles);
        try {
            sysUserService.updateUser(sysUser);
            map.put("msg","success");
        } catch (Exception e) {
            map.put("msg","fail");
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 添加用户
     * @param
     * @return
     */
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"user:create"})
    public Map<String, Object> addUser(SysUser sysUser) {
        Map<String, Object> map = new HashedMap();
        //默认状态为0
        sysUser.setUserAvailable(0);
        try {
            passwordHelper.encryptPassword(sysUser);
            sysUserService.addUser(sysUser);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", e.getMessage());
        }
        return map;
    }

    /**
     * 改变用户状态
     * @param id
     * @return
     */
    @RequestMapping(value = "changeStatus", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"user:update"})
    public Map<String, Object> changeStatus(Long id) {
        Map<String, Object> map = new HashedMap();
        SysUser sysUser= sysUserService.findOne(id);
        if (sysUser.getUserAvailable()==1){
            sysUser.setUserAvailable(0);
        }else{
            sysUser.setUserAvailable(1);
        }
        try {
            sysUserService.updateUser(sysUser);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", e.getMessage());
        }
        return map;
    }
    @RequestMapping("editPwd")
    @ResponseBody
    @CheckPermission(permission={"user:update"})
    public Map<String,Object>editPwd(String id,String userPassword){
        Map<String, Object> map = new HashedMap();
        SysUser sysUser=sysUserService.findOne(Long.valueOf(id));
        sysUser.setUserPassword(userPassword);
        passwordHelper.encryptPassword(sysUser);
        try {
            sysUserService.updateUser(sysUser);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", e.getMessage());
        }
        return map;
    }
}

